package sk.hackcraft.multibox.server;

import java.util.HashSet;
import java.util.Set;

import org.gstreamer.State;
import org.gstreamer.elements.PlayBin2;

public class Playlist {
	private static final long serialVersionUID = 7408515861798878898L;

	public class SongRecord {		
		final public Song song;
		public SongRecord next = null;
		
		public SongRecord(Song song) {
			this.song = song;
		}
	}
	
	static public interface ChangeListener {
		public void onPlaylistChange();
	}
	
	private SongRecord playing = null;
	private SongRecord first = null;
	private SongRecord last = null;
	private Set<ChangeListener> onChangeListeners = new HashSet<ChangeListener>();
	
	public Playlist() {
		super();
	}
	
	public synchronized void addSongToPlay(Song song) {
		if(first == null) {
			first = new SongRecord(song);
			playing = last = first.next = first;
			playNextSong();
		} else {
			SongRecord record = new SongRecord(song);
			record.next = first;
			last.next = record;
			last = record;
		}
		
        Set<ChangeListener> listeners = null;
        
        synchronized(onChangeListeners) {
        	listeners = new HashSet<ChangeListener>(onChangeListeners);
        }
        
        for(ChangeListener listener : listeners) {
        	listener.onPlaylistChange();
        }
	}
	
	private synchronized void playNextSong() {
		if(playing != null) {
			playing = playing.next;
			
			Song song = playing.song;
	        PlayBin2 playbin = new PlayBin2(song.toString());
	        playbin.setInputFile(song.file);
	        playbin.connect(new PlayBin2.ABOUT_TO_FINISH() {
				@Override
				public void aboutToFinish(PlayBin2 bin) {
					Playlist.this.playNextSong();
				}
			});
	        
	        playbin.setState(State.PLAYING);
	        
	        Set<ChangeListener> listeners = null;
	        
	        synchronized(onChangeListeners) {
	        	listeners = new HashSet<ChangeListener>(onChangeListeners);
	        }
	        
	        for(ChangeListener listener : listeners) {
	        	listener.onPlaylistChange();
	        }
		}
	}
	
	public SongRecord getPlaying() {
		return playing;
	}
	
	public void addChangeListener(ChangeListener listener) {
		synchronized(onChangeListeners) {
			onChangeListeners.add(listener);
		}
	}
	
	public void removeChangeListener(ChangeListener listener) {
		synchronized(onChangeListeners) {
			onChangeListeners.remove(listener);
		}
	}
}
